<template>
  <div class="emerrecord">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.record_delete"
                     @click="handleDelete">删 除
          </el-button>
          <el-button type="success"
                     size="small"
                     plain
                     v-if="permission.record_import"
                     icon="el-icon-upload2"
                     @click="handleImport">导入
          </el-button>
          <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permission.record_export"
                     @click="handleExport">导出
          </el-button>
        </template>
        <!-- 附件表格自定义 -->
        <template slot="xgfj" slot-scope="scope">
          <div class="enclosure_div" v-if="scope.row['xgfj']!=''">
            <a :href="downloadHead + scope.row['xgfj']">
              <i class="el-icon-download"></i>下载附件
            </a>
          </div>
          <div class="enclosure_div" v-else>
            -
          </div>
        </template>
        <!-- 附件表单自定义 -->
        <template slot="xgfjForm">
          <div>
            <el-upload
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="xgfjFileList"
              :before-upload="beforeUploadxgfj"
              :on-remove="handleRemovexgfj"
              :on-success="uploadxgfjSuccess"
            >
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </div>
        </template>
        <!-- 应对事故类型表格自定义 -->
        <template slot="sglx" slot-scope="scope">
          <div>{{cellChemicals(scope.row)}}</div>
        </template>
      </avue-crud>
      <el-dialog title="应急装备据导入"
                 append-to-body
                 :visible.sync="excelBox"
                 width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false"
                   :upload-before="beforeUpload"
                   :upload-after="uploadAfter"
                   :upload-error="uploadError"
        >
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/emer/record";
  import {mapGetters} from "vuex";
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import {getydsglx} from "@/api/emer/eqpt";
  import {getToken} from "@/util/auth";
  import {getFzrLinkInfo} from "@/api/mmhi/prod_unit";

  export default {
    data() {
      return {
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              showFileList: false,
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/emerRecord/import"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },

        cellChemicalsList: {},
        //附件
        xgfjFileList: [],
        downloadHead: "/api/fileManager/download/",
        SetHeaders: { "Blade-Auth": getToken() },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "应急记录名称",
              prop: "yjjlmc",
              searchLabelWidth: 120,
              align: "center",
              maxlength:32,
              search: true,
              rules: [{
                required: true,
                message: "请输入应急记录名称",
                trigger: "blur"
              }]
            },
            {
              label: "事故发生地点",
              prop: "sgfsdd",
              align: "center",
              maxlength:64,
              rules: [{
                required: true,
                message: "请输入事故发生地点",
                trigger: "blur"
              }]
            },
            {
              label: "事故发生日期",
              prop: "sgfssj",
              align: "center",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              rules: [{
                required: true,
                message: "请输入事故发生日期",
                trigger: "blur"
              }]
            },
            {
              label: "事故类型",
              prop: "sglx",
              align: "center",
              multiple: true,
              slot: true,
              type: "tree",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_eqpt_yjsglx",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请输入事故类型",
                trigger: "blur"
              }]
            },
            {
              label: "安全负责人",
              prop: "aqfzr",
              align: "center",
              type: "select",
              dicUrl: "/api/prodUnitManage/bladeProdUnit/getFzrList",
              props: {
                value: "realName"
              },
              rules: [{
                required: true,
                message: "请输入安全负责人",
                trigger: "blur"
              }]
            },
            {
              label: "负责人联系电话",
              prop: "fzrlxdh",
              align: "center",
              disabled: true,
            },
            {
              label: "负责人部门",
              prop: "fzrbm",
              align: "center",
              disabled: true,
            },
            {
              label: "相关附件",
              prop: "xgfj",
              align: "center",
              slot: true,
              formslot: true,
              rules: [{
                required: false,
                message: "请输入相关附件",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              maxlength:500,
              span: 24,
              type: "textarea",
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    watch: {
      'form.aqfzr':{
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getFzrLinkInfo(val).then(res=>{
              this.form.fzrbm = res.data.data[0].deptName;
              this.form.fzrlxdh = res.data.data[0].phone;
            });
          }
        },
        immediate: true
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.record_add, false),
          viewBtn: this.vaildData(this.permission.record_view, false),
          delBtn: this.vaildData(this.permission.record_delete, false),
          editBtn: this.vaildData(this.permission.record_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      this.initData()
      this.getydsglx()
    },
    methods: {
      //导出摸板
      handleTemplate() {
        window.open(`/api/emerTeam/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      // 导入前判断
      beforeUpload(file, done, loading) {
        this.uploadFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
          loading()
        } else {
          done()
        }
      },
      // 导入成功后1
      uploadAfter1() {
        this.excelBox = false;
        this.$message.success("上传成功");
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      // 导入成功后
      uploadAfter(res, done) {
        done();
        if(this.uploadFailed === true) {
          return;
        }
        this.uploadAfter1()
      },
      // 导入失败后
      uploadError(error, column) {
        console.log(error,column);
        this.uploadFailed = true;
      },
      //打开导入弹窗
      handleImport() {
        this.excelBox = true;
      },
      //导出应急装备
      handleExport() {
        this.$confirm("是否导出应急装备数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let yjjlmc = this.query.yjjlmc !== undefined && this.query.yjjlmc !== "" && this.query.yjjlmc !== null ? this.query.yjjlmc : "";
          window.open(`/api/emerRecord/export?${this.website.tokenHeader}=${getToken()}&yjjlmc=${yjjlmc}`);
        });
      },
      // 获取应对事故类型列表
      getydsglx() {
        getydsglx().then(res => {
          this.cellChemicalsList = {};
          res.data.data.forEach(item => {
            this.cellChemicalsList[item.dictKey] = item.dictValue;
          });
        })
      },
      // 显示应对事故类型列
      cellChemicals(row) {
        if (row.sglx === undefined || typeof row.sglx === "object") {
          return "";
        }
        var arr = row.sglx.split(",");
        var faults = [];
        for (let i = 0; i < arr.length; i++) {
          var fault = this.cellChemicalsList[arr[i]] === undefined ? arr[i] : this.cellChemicalsList[arr[i]];
          faults.push(fault);
        }
        return faults.join("|");
      },
      /**
       * 上传附件
       */

      // 上传附件前
      beforeUploadxgfj() {
        var isLimit = this.xgfjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传附件成功
      uploadxgfjSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.xgfjFileList = fileList;
        this.form.xgfj = response.data.id;
        console.log(this.form.xgfj)
      },

      // 删除附件
      handleRemovexgfj(file, fileList) {
        this.xgfjFileList = fileList;
        this.form.xgfj = "";
      },
      // 初始化数据
      initData() {
        var tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;
        getDeptList(tenantId).then(res => {
          const column = this.findObject(this.option.column, "fzrbm");
          column.dicData = res.data.data;
        }).then(() => {

        });
      },
      rowSave(row, done, loading) {
        row.sglx = this.form.sglx.join(",")
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.xgfjFileList = []
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            if (type === "edit") {
              if (JSON.stringify(this.form.bladeFile) != "{}")
                this.xgfjFileList.push({
                  name: this.form.bladeFile.fileName,
                  response: {
                    code: 200,
                    success: true,
                    msg: "操作成功",
                    data: this.form.bladeFile
                  }
                });
            }
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss" scpoed>
  .emerrecord {
    .enclosure_div {
      a {
        font-size: 12px;
        color: #409eff;

        i {
          margin-right: 5px;
        }
      }
    }
  }
</style>
